<?php
/*
 * @ https://EasyToYou.eu - IonCube v11 Decoder Online
 * @ PHP 7.2 & 7.3
 * @ Decoder version: 1.1.6
 * @ Release: 10/08/2022
 */

// Decoded file for php version 71.
require_once "AopEncrypt.php";
require_once "AopCertification.php";
require_once "EncryptParseItem.php";
require_once "EncryptResponseData.php";
require_once "SignData.php";
class AopCertClient
{
    public $appCertSN;
    public $alipayCertSN;
    public $alipayRootCertSN;
    public $alipayRootCertContent;
    public $isCheckAlipayPublicCert;
    public $appId;
    public $rsaPrivateKeyFilePath;
    public $rsaPrivateKey;
    public $gatewayUrl = "https://openapi.alipay.com/gateway.do";
    public $format = "json";
    public $apiVersion = "1.0";
    public $postCharset = "UTF-8";
    public $alipayPublicKey;
    public $alipayrsaPublicKey;
    public $debugInfo = false;
    public $signType = "RSA";
    public $encryptKey;
    public $encryptType = "AES";
    protected $alipaySdkVersion = "alipay-sdk-php-2020-04-15";
    private $fileCharset = "UTF-8";
    private $RESPONSE_SUFFIX = "_response";
    private $ERROR_RESPONSE = "error_response";
    private $SIGN_NODE_NAME = "sign";
    private $ALIPAY_CERT_SN = "alipay_cert_sn";
    private $ENCRYPT_XML_NODE_NAME = "response_encrypted";
    private $needEncrypt = false;
    private $targetServiceUrl = "";
    public function getCertSN($certPath)
    {
        $cert = file_get_contents($certPath);
        $ssl = openssl_x509_parse($cert);
        $SN = md5(array2string(array_reverse($ssl["issuer"])) . $ssl["serialNumber"]);
        return $SN;
    }
    public function getRootCertSN($certPath)
    {
        $cert = file_get_contents($certPath);
        $this->alipayRootCertContent = $cert;
        $array = explode("-----END CERTIFICATE-----", $cert);
        $SN = NULL;
        for ($i = 0; $i < count($array) - 1; $i++) {
            $ssl[$i] = openssl_x509_parse($array[$i] . "-----END CERTIFICATE-----");
            if(strpos($ssl[$i]["serialNumber"], "0x") === 0) {
                $ssl[$i]["serialNumber"] = $this->hex2dec($ssl[$i]["serialNumber"]);
            }
            if($ssl[$i]["signatureTypeLN"] == "sha1WithRSAEncryption" || $ssl[$i]["signatureTypeLN"] == "sha256WithRSAEncryption") {
                if($SN == NULL) {
                    $SN = md5(array2string(array_reverse($ssl[$i]["issuer"])) . $ssl[$i]["serialNumber"]);
                } else {
                    $SN = $SN . "_" . md5(array2string(array_reverse($ssl[$i]["issuer"])) . $ssl[$i]["serialNumber"]);
                }
            }
        }
        return $SN;
    }
    public function hex2dec($hex)
    {
        $dec = 0;
        $len = strlen($hex);
        for ($i = 1; $i <= $len; $i++) {
            $dec = bcadd($dec, bcmul(strval(hexdec($hex[$i - 1])), bcpow("16", strval($len - $i))));
        }
        return round($dec, 0);
    }
    public function getPublicKey($certPath)
    {
        $cert = file_get_contents($certPath);
        $pkey = openssl_pkey_get_public($cert);
        $keyData = openssl_pkey_get_details($pkey);
        $public_key = str_replace("-----BEGIN PUBLIC KEY-----", "", $keyData["key"]);
        $public_key = trim(str_replace("-----END PUBLIC KEY-----", "", $public_key));
        return $public_key;
    }
    public function rsaCheckV1($params, $rsaPublicKeyFilePath, $signType = "RSA")
    {
        $sign = $params["sign"];
        unset($params["sign"]);
        unset($params["sign_type"]);
        return $this->verify($this->getCheckSignContent($params), $sign, $rsaPublicKeyFilePath, $signType);
    }
    public function rsaCheckV2($params, $rsaPublicKeyFilePath, $signType = "RSA")
    {
        $sign = $params["sign"];
        unset($params["sign"]);
        unset($params["sign_type"]);
        return $this->verify($this->getCheckSignContent($params), $sign, $rsaPublicKeyFilePath, $signType);
    }
    public function getCheckSignContent($params)
    {
        ksort($params);
        $stringToBeSigned = "";
        $i = 0;
        foreach ($params as $k => $v) {
            $v = $this->characet($v, $this->postCharset);
            if($i == 0) {
                $stringToBeSigned .= (string) $k . "=" . (string) $v;
            } else {
                $stringToBeSigned .= "&" . (string) $k . "=" . (string) $v;
            }
            $i++;
        }
        unset($k);
        unset($v);
        return $stringToBeSigned;
    }
    public function checkSignAndDecrypt($params, $rsaPublicKeyPem, $rsaPrivateKeyPem, $isCheckSign, $isDecrypt, $signType = "RSA")
    {
        $charset = $params["charset"];
        $bizContent = $params["biz_content"];
        if($isCheckSign && !$this->rsaCheckV2($params, $rsaPublicKeyPem, $signType)) {
            echo "<br/>checkSign failure<br/>";
            exit;
        }
        if($isDecrypt) {
            return $this->rsaDecrypt($bizContent, $rsaPrivateKeyPem, $charset);
        }
        return $bizContent;
    }
    public function encryptAndSign($bizContent, $rsaPublicKeyPem, $rsaPrivateKeyPem, $charset, $isEncrypt, $isSign, $signType = "RSA")
    {
        if($isEncrypt && $isSign) {
            $encrypted = $this->rsaEncrypt($bizContent, $rsaPublicKeyPem, $charset);
            $sign = $this->sign($encrypted, $signType);
            $response = "<?xml version=\"1.0\" encoding=\"" . $charset . "\"?><alipay><response>" . $encrypted . "</response><encryption_type>RSA</encryption_type><sign>" . $sign . "</sign><sign_type>" . $signType . "</sign_type></alipay>";
            return $response;
        }
        if($isEncrypt && !$isSign) {
            $encrypted = $this->rsaEncrypt($bizContent, $rsaPublicKeyPem, $charset);
            $response = "<?xml version=\"1.0\" encoding=\"" . $charset . "\"?><alipay><response>" . $encrypted . "</response><encryption_type>" . $signType . "</encryption_type></alipay>";
            return $response;
        }
        if(!$isEncrypt && $isSign) {
            $sign = $this->sign($bizContent, $signType);
            $response = "<?xml version=\"1.0\" encoding=\"" . $charset . "\"?><alipay><response>" . $bizContent . "</response><sign>" . $sign . "</sign><sign_type>" . $signType . "</sign_type></alipay>";
            return $response;
        }
        $response = "<?xml version=\"1.0\" encoding=\"" . $charset . "\"?>" . $bizContent;
        return $response;
    }
    public function rsaEncrypt($data, $rsaPublicKeyFilePath, $charset)
    {
        if($this->checkEmpty($this->alipayPublicKey)) {
            $pubKey = $this->alipayrsaPublicKey;
            $res = "-----BEGIN PUBLIC KEY-----\n" . wordwrap($pubKey, 64, "\n", true) . "\n-----END PUBLIC KEY-----";
        } else {
            $pubKey = file_get_contents($rsaPublicKeyFilePath);
            $res = openssl_get_publickey($pubKey);
        }
        $res or exit("支付宝RSA公钥错误。请检查公钥文件格式是否正确");
        $blocks = $this->splitCN($data, 0, 30, $charset);
        $_obfuscated_63687274657874C2A0_ = NULL;
        $_obfuscated_656E636F646573C2A0_ = [];
        foreach ($blocks as $n => $block) {
            if(!openssl_public_encrypt($block, $_obfuscated_63687274657874C2A0_, $res)) {
                echo "<br/>" . openssl_error_string() . "<br/>";
            }
            $encodes[] = $_obfuscated_63687274657874C2A0_;
        }
        $chrtext = implode(",", $encodes);
        return base64_encode($chrtext);
    }
    public function rsaDecrypt($data, $rsaPrivateKeyPem, $charset)
    {
        if($this->checkEmpty($this->rsaPrivateKeyFilePath)) {
            $priKey = $this->rsaPrivateKey;
            $res = "-----BEGIN RSA PRIVATE KEY-----\n" . wordwrap($priKey, 64, "\n", true) . "\n-----END RSA PRIVATE KEY-----";
        } else {
            $priKey = file_get_contents($this->rsaPrivateKeyFilePath);
            $res = openssl_get_privatekey($priKey);
        }
        $res or exit("您使用的私钥格式错误，请检查RSA私钥配置");
        $decodes = explode(",", $data);
        $strnull = "";
        $dcyCont = "";
        foreach ($decodes as $n => $decode) {
            if(!openssl_private_decrypt($decode, $dcyCont, $res)) {
                echo "<br/>" . openssl_error_string() . "<br/>";
            }
            $strnull .= $dcyCont;
        }
        return $strnull;
    }
    public function splitCN($cont, $n = 0, $subnum, $charset)
    {
        $arrr = [];
        $i = $n;
        while ($i < strlen($cont)) {
            $res = $this->subCNchar($cont, $i, $subnum, $charset);
            if(!empty($res)) {
                $arrr[] = $res;
            }
            $i += $subnum;
        }
        return $arrr;
    }
    public function subCNchar($str, $start = 0, $length, $charset = "gbk")
    {
        if(strlen($str) <= $length) {
            return $str;
        }
        $re["utf-8"] = "/[\1-]|[�-�][�-�]|[�-�][�-�]{2}|[�-�][�-�]{3}/";
        $re["gb2312"] = "/[\1-]|[�-�][�-�]/";
        $re["gbk"] = "/[\1-]|[�-�][@-�]/";
        $re["big5"] = "/[\1-]|[�-�]([@-~]|�-�])/";
        preg_match_all($re[$charset], $str, $match);
        $slice = join("", array_slice($match[0], $start, $length));
        return $slice;
    }
    public function sdkExecute($request, $appAuthToken = NULL)
    {
        $this->setupCharsets($request);
        $params["app_id"] = $this->appId;
        $params["method"] = $request->getApiMethodName();
        $params["format"] = $this->format;
        $params["sign_type"] = $this->signType;
        $params["timestamp"] = date("Y-m-d H:i:s");
        $params["alipay_sdk"] = $this->alipaySdkVersion;
        $params["charset"] = $this->postCharset;
        $version = $request->getApiVersion();
        $params["version"] = $this->checkEmpty($version) ? $this->apiVersion : $version;
        $params["app_cert_sn"] = $this->appCertSN;
        $params["alipay_root_cert_sn"] = $this->alipayRootCertSN;
        if($notify_url = $request->getNotifyUrl()) {
            $params["notify_url"] = $notify_url;
        }
        $params["app_auth_token"] = $appAuthToken;
        $dict = $request->getApiParas();
        $params["biz_content"] = $dict["biz_content"];
        ksort($params);
        $params["sign"] = $this->generateSign($params, $this->signType);
        foreach ($params as &$value) {
            $value = $this->characet($value, $params["charset"]);
        }
        return http_build_query($params);
    }
    public function pageExecute($request, $httpmethod = "POST", $appAuthToken = NULL)
    {
        $this->setupCharsets($request);
        if(strcasecmp($this->fileCharset, $this->postCharset)) {
            throw new Exception("文件编码：[" . $this->fileCharset . "] 与表单提交编码：[" . $this->postCharset . "]两者不一致!");
        }
        $iv = NULL;
        if(!$this->checkEmpty($request->getApiVersion())) {
            $iv = $request->getApiVersion();
        } else {
            $iv = $this->apiVersion;
        }
        $sysParams["app_id"] = $this->appId;
        $sysParams["version"] = $iv;
        $sysParams["format"] = $this->format;
        $sysParams["sign_type"] = $this->signType;
        $sysParams["method"] = $request->getApiMethodName();
        $sysParams["timestamp"] = date("Y-m-d H:i:s");
        $sysParams["alipay_sdk"] = $this->alipaySdkVersion;
        $sysParams["terminal_type"] = $request->getTerminalType();
        $sysParams["terminal_info"] = $request->getTerminalInfo();
        $sysParams["prod_code"] = $request->getProdCode();
        $sysParams["notify_url"] = $request->getNotifyUrl();
        $sysParams["return_url"] = $request->getReturnUrl();
        $sysParams["charset"] = $this->postCharset;
        $sysParams["app_auth_token"] = $appAuthToken;
        $sysParams["app_cert_sn"] = $this->appCertSN;
        $sysParams["alipay_root_cert_sn"] = $this->alipayRootCertSN;
        $apiParams = $request->getApiParas();
        if(method_exists($request, "getNeedEncrypt") && $request->getNeedEncrypt()) {
            $sysParams["encrypt_type"] = $this->encryptType;
            if($this->checkEmpty($apiParams["biz_content"])) {
                throw new Exception(" api request Fail! The reason : encrypt request is not supperted!");
            }
            if($this->checkEmpty($this->encryptKey) || $this->checkEmpty($this->encryptType)) {
                throw new Exception(" encryptType and encryptKey must not null! ");
            }
            if("AES" != $this->encryptType) {
                throw new Exception("加密类型只支持AES");
            }
            $enCryptContent = encrypt($apiParams["biz_content"], $this->encryptKey);
            $apiParams["biz_content"] = $enCryptContent;
        }
        $totalParams = array_merge($apiParams, $sysParams);
        $preSignStr = $this->getSignContent($totalParams);
        $totalParams["sign"] = $this->generateSign($totalParams, $this->signType);
        if("GET" == strtoupper($httpmethod)) {
            $preString = $this->getSignContentUrlencode($totalParams);
            $requestUrl = $this->gatewayUrl . "?" . $preString;
            return $requestUrl;
        }
        return $this->buildRequestForm($totalParams);
    }
    public function getSignContentUrlencode($params)
    {
        ksort($params);
        $stringToBeSigned = "";
        $i = 0;
        foreach ($params as $k => $v) {
            if(false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
                $v = $this->characet($v, $this->postCharset);
                if($i == 0) {
                    $stringToBeSigned .= (string) $k . "=" . urlencode($v);
                } else {
                    $stringToBeSigned .= "&" . (string) $k . "=" . urlencode($v);
                }
                $i++;
            }
        }
        unset($k);
        unset($v);
        return $stringToBeSigned;
    }
    protected function buildRequestForm($para_temp)
    {
        $sHtml = "<form id='alipaysubmit' name='alipaysubmit' action='" . $this->gatewayUrl . "?charset=" . trim($this->postCharset) . "' method='POST'>";
        while (list($key, $val) = $this->fun_adm_each($para_temp)) {
            if(false === $this->checkEmpty($val)) {
                $val = str_replace("'", "&apos;", $val);
                $sHtml .= "<input type='hidden' name='" . $key . "' value='" . $val . "'/>";
            }
        }
        $sHtml = $sHtml . "<input type='submit' value='ok' style='display:none;''></form>";
        $sHtml = $sHtml . "<script>document.forms['alipaysubmit'].submit();</script>";
        return $sHtml;
    }
    protected function fun_adm_each(&$array)
    {
        $res = [];
        $key = key($array);
        if($key !== NULL) {
            next($array);
            $res["value"] = $array[$key];
            $res[1] = $res["value"];
            $res["key"] = $key;
            $res[0] = $res["key"];
        } else {
            $res = false;
        }
        return $res;
    }
    public function execute($request, $authToken = NULL, $appInfoAuthtoken = NULL, $targetAppId = NULL)
    {
        $this->setupCharsets($request);
        if(strcasecmp($this->fileCharset, $this->postCharset)) {
            throw new Exception("文件编码：[" . $this->fileCharset . "] 与表单提交编码：[" . $this->postCharset . "]两者不一致!");
        }
        $iv = NULL;
        if(!$this->checkEmpty($request->getApiVersion())) {
            $iv = $request->getApiVersion();
        } else {
            $iv = $this->apiVersion;
        }
        $sysParams["app_id"] = $this->appId;
        $sysParams["version"] = $iv;
        $sysParams["format"] = $this->format;
        $sysParams["sign_type"] = $this->signType;
        $sysParams["method"] = $request->getApiMethodName();
        $sysParams["timestamp"] = date("Y-m-d H:i:s");
        $sysParams["auth_token"] = $authToken;
        $sysParams["alipay_sdk"] = $this->alipaySdkVersion;
        $sysParams["terminal_type"] = $request->getTerminalType();
        $sysParams["terminal_info"] = $request->getTerminalInfo();
        $sysParams["prod_code"] = $request->getProdCode();
        $sysParams["notify_url"] = $request->getNotifyUrl();
        $sysParams["charset"] = $this->postCharset;
        $sysParams["app_auth_token"] = $appInfoAuthtoken;
        $sysParams["app_cert_sn"] = $this->appCertSN;
        $sysParams["alipay_root_cert_sn"] = $this->alipayRootCertSN;
        $sysParams["target_app_id"] = $targetAppId;
        if(!$this->checkEmpty($this->targetServiceUrl)) {
            $sysParams["ws_service_url"] = $this->targetServiceUrl;
        }
        $apiParams = $request->getApiParas();
        if(method_exists($request, "getNeedEncrypt") && $request->getNeedEncrypt()) {
            $sysParams["encrypt_type"] = $this->encryptType;
            if($this->checkEmpty($apiParams["biz_content"])) {
                throw new Exception(" api request Fail! The reason : encrypt request is not supperted!");
            }
            if($this->checkEmpty($this->encryptKey) || $this->checkEmpty($this->encryptType)) {
                throw new Exception(" encryptType and encryptKey must not null! ");
            }
            if("AES" != $this->encryptType) {
                throw new Exception("加密类型只支持AES");
            }
            $enCryptContent = encrypt($apiParams["biz_content"], $this->encryptKey);
            $apiParams["biz_content"] = $enCryptContent;
        }
        $sysParams["sign"] = $this->generateSign(array_merge($apiParams, $sysParams), $this->signType);
        $requestUrl = $this->gatewayUrl . "?";
        foreach ($sysParams as $sysParamKey => $sysParamValue) {
            $requestUrl .= $sysParamKey . "=" . urlencode($this->characet($sysParamValue, $this->postCharset)) . "&";
        }
        $requestUrl = substr($requestUrl, 0, -1);
        try {
            $resp = $this->curl($requestUrl, $apiParams);
        } catch (Exception $e) {
            $this->logCommunicationError($sysParams["method"], $requestUrl, "HTTP_ERROR_" . $e->getCode(), $e->getMessage());
            return false;
        }
        $respWellFormed = false;
        $r = iconv($this->postCharset, $this->fileCharset . "//IGNORE", $resp);
        $signData = NULL;
        if("json" == $this->format) {
            $respObject = json_decode($r);
            if(NULL !== $respObject) {
                $respWellFormed = true;
                $signData = $this->parserJSONSignData($request, $resp, $respObject);
            }
        } elseif("xml" == $this->format) {
            $disableLibxmlEntityLoader = libxml_disable_entity_loader(true);
            $respObject = @simplexml_load_string($resp);
            if(false !== $respObject) {
                $respWellFormed = true;
                $signData = $this->parserXMLSignData($request, $resp);
            }
            libxml_disable_entity_loader($disableLibxmlEntityLoader);
        }
        if(false === $respWellFormed) {
            $this->logCommunicationError($sysParams["method"], $requestUrl, "HTTP_RESPONSE_NOT_WELL_FORMED", $resp);
            return false;
        }
        $this->checkResponseSign($request, $signData, $resp, $respObject);
        if(method_exists($request, "getNeedEncrypt") && $request->getNeedEncrypt()) {
            if("json" == $this->format) {
                $resp = $this->encryptJSONSignSource($request, $resp);
                $r = iconv($this->postCharset, $this->fileCharset . "//IGNORE", $resp);
                $respObject = json_decode($r);
            } else {
                $resp = $this->encryptXMLSignSource($request, $resp);
                $r = iconv($this->postCharset, $this->fileCharset . "//IGNORE", $resp);
                $disableLibxmlEntityLoader = libxml_disable_entity_loader(true);
                $respObject = @simplexml_load_string($r);
                libxml_disable_entity_loader($disableLibxmlEntityLoader);
            }
        }
        return $respObject;
    }
    private function setupCharsets($request)
    {
        if($this->checkEmpty($this->postCharset)) {
            $this->postCharset = "UTF-8";
        }
        $str = preg_match("/[\\x80-\\xff]/", $this->appId) ? $this->appId : print_r($request, true);
        $this->fileCharset = mb_detect_encoding($str, "UTF-8, GBK") == "UTF-8" ? "UTF-8" : "GBK";
    }
    protected function checkEmpty($value)
    {
        if(!isset($value)) {
            return true;
        }
        if($value === NULL) {
            return true;
        }
        if(trim($value) === "") {
            return true;
        }
        return false;
    }
    public function generateSign($params, $signType = "RSA")
    {
        return $this->sign($this->getSignContent($params), $signType);
    }
    public function rsaSign($params, $signType = "RSA")
    {
        return $this->sign($this->getSignContent($params), $signType);
    }
    protected function sign($data, $signType = "RSA")
    {
        if($this->checkEmpty($this->rsaPrivateKeyFilePath)) {
            $priKey = $this->rsaPrivateKey;
            $res = "-----BEGIN RSA PRIVATE KEY-----\n" . wordwrap($priKey, 64, "\n", true) . "\n-----END RSA PRIVATE KEY-----";
        } else {
            $priKey = file_get_contents($this->rsaPrivateKeyFilePath);
            $res = openssl_get_privatekey($priKey);
        }
        $res or exit("您使用的私钥格式错误，请检查RSA私钥配置");
        if("RSA2" == $signType) {
            openssl_sign($data, $sign, $res, OPENSSL_ALGO_SHA256);
        } else {
            openssl_sign($data, $sign, $res);
        }
        if(!$this->checkEmpty($this->rsaPrivateKeyFilePath)) {
            openssl_free_key($res);
        }
        $sign = base64_encode($sign);
        return $sign;
    }
    public function getSignContent($params)
    {
        ksort($params);
        $stringToBeSigned = "";
        $i = 0;
        foreach ($params as $k => $v) {
            if(false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
                $v = $this->characet($v, $this->postCharset);
                if($i == 0) {
                    $stringToBeSigned .= (string) $k . "=" . (string) $v;
                } else {
                    $stringToBeSigned .= "&" . (string) $k . "=" . (string) $v;
                }
                $i++;
            }
        }
        unset($k);
        unset($v);
        return $stringToBeSigned;
    }
    public function alonersaSign($data, $privatekey, $signType = "RSA", $keyfromfile = false)
    {
        if(!$keyfromfile) {
            $priKey = $privatekey;
            $res = "-----BEGIN RSA PRIVATE KEY-----\n" . wordwrap($priKey, 64, "\n", true) . "\n-----END RSA PRIVATE KEY-----";
        } else {
            $priKey = file_get_contents($privatekey);
            $res = openssl_get_privatekey($priKey);
        }
        $res or exit("您使用的私钥格式错误，请检查RSA私钥配置");
        if("RSA2" == $signType) {
            openssl_sign($data, $sign, $res, OPENSSL_ALGO_SHA256);
        } else {
            openssl_sign($data, $sign, $res);
        }
        if($keyfromfile) {
            openssl_free_key($res);
        }
        $sign = base64_encode($sign);
        return $sign;
    }
    public function characet($data, $targetCharset)
    {
        if(!empty($data)) {
            $fileType = $this->fileCharset;
            if(strcasecmp($fileType, $targetCharset) != 0) {
                $data = mb_convert_encoding($data, $targetCharset, $fileType);
            }
        }
        return $data;
    }
    protected function curl($url, $postFields = NULL)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_FAILONERROR, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
        $postBodyString = "";
        $encodeArray = [];
        $postMultipart = false;
        if(is_array($postFields) && 0 < count($postFields)) {
            foreach ($postFields as $k => $v) {
                if("@" != substr($v, 0, 1)) {
                    $postBodyString .= $k . "=" . urlencode($this->characet($v, $this->postCharset)) . "&";
                    $encodeArray[$k] = $this->characet($v, $this->postCharset);
                } else {
                    $postMultipart = true;
                    $encodeArray[$k] = new CURLFile(substr($v, 1));
                }
            }
            unset($k);
            unset($v);
            curl_setopt($ch, CURLOPT_POST, true);
            if($postMultipart) {
                curl_setopt($ch, CURLOPT_POSTFIELDS, $encodeArray);
            } else {
                curl_setopt($ch, CURLOPT_POSTFIELDS, substr($postBodyString, 0, -1));
            }
        }
        if(!$postMultipart) {
            $headers = ["content-type: application/x-www-form-urlencoded;charset=" . $this->postCharset];
            curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $reponse = curl_exec($ch);
        if(curl_errno($ch)) {
            throw new Exception(curl_error($ch), 0);
        }
        $httpStatusCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if(200 !== $httpStatusCode) {
            throw new Exception($reponse, $httpStatusCode);
        }
        curl_close($ch);
        return $reponse;
    }
    protected function getMillisecond()
    {
        list($s1, $s2) = explode(" ", microtime());
        return (double) sprintf("%.0f", (floatval($s1) + floatval($s2)) * 1000);
    }
    protected function logCommunicationError($apiName, $requestUrl, $errorCode, $responseTxt)
    {
        $logData = [date("Y-m-d H:i:s"), $apiName, $this->appId, PHP_OS, $this->alipaySdkVersion, $requestUrl, $errorCode, str_replace("\n", "", $responseTxt)];
        echo json_encode($logData);
    }
    public function parserJSONSignData($request, $responseContent, $responseJSON)
    {
        $signData = new SignData();
        $signData->sign = $this->parserJSONSign($responseJSON);
        $signData->signSourceData = $this->parserJSONSignSource($request, $responseContent);
        return $signData;
    }
    public function parserJSONSign($responseJSon)
    {
        return $responseJSon->sign;
    }
    public function parserJSONSignSource($request, $responseContent)
    {
        $apiName = $request->getApiMethodName();
        $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
        $rootIndex = strpos($responseContent, $rootNodeName);
        $errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
        if(0 < $rootIndex) {
            return $this->parserJSONSource($responseContent, $rootNodeName, $rootIndex);
        }
        if(0 < $errorIndex) {
            return $this->parserJSONSource($responseContent, $this->ERROR_RESPONSE, $errorIndex);
        }
        return NULL;
    }
    public function parserJSONSource($responseContent, $nodeName, $nodeIndex)
    {
        $signDataStartIndex = $nodeIndex + strlen($nodeName) + 2;
        if(strrpos($responseContent, $this->ALIPAY_CERT_SN)) {
            $signIndex = strrpos($responseContent, "\"" . $this->ALIPAY_CERT_SN . "\"");
        } else {
            $signIndex = strrpos($responseContent, "\"" . $this->SIGN_NODE_NAME . "\"");
        }
        $signDataEndIndex = $signIndex - 1;
        $indexLen = $signDataEndIndex - $signDataStartIndex;
        if($indexLen < 0) {
            return NULL;
        }
        return substr($responseContent, $signDataStartIndex, $indexLen);
    }
    public function parserXMLSignData($request, $responseContent)
    {
        $signData = new SignData();
        $signData->sign = $this->parserXMLSign($responseContent);
        $signData->signSourceData = $this->parserXMLSignSource($request, $responseContent);
        return $signData;
    }
    public function parserXMLSign($responseContent)
    {
        if(strrpos($responseContent, $this->ALIPAY_CERT_SN)) {
            $signNodeName = "<" . $this->ALIPAY_CERT_SN . ">";
            $signEndNodeName = "</" . $this->ALIPAY_CERT_SN . ">";
        } else {
            $signNodeName = "<" . $this->SIGN_NODE_NAME . ">";
            $signEndNodeName = "</" . $this->SIGN_NODE_NAME . ">";
        }
        $indexOfSignNode = strpos($responseContent, $signNodeName);
        $indexOfSignEndNode = strpos($responseContent, $signEndNodeName);
        if($indexOfSignNode < 0 || $indexOfSignEndNode < 0) {
            return NULL;
        }
        $nodeIndex = $indexOfSignNode + strlen($signNodeName);
        $indexLen = $indexOfSignEndNode - $nodeIndex;
        if($indexLen < 0) {
            return NULL;
        }
        return substr($responseContent, $nodeIndex, $indexLen);
    }
    public function parserXMLSignSource($request, $responseContent)
    {
        $apiName = $request->getApiMethodName();
        $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
        $rootIndex = strpos($responseContent, $rootNodeName);
        $errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
        if(0 < $rootIndex) {
            return $this->parserXMLSource($responseContent, $rootNodeName, $rootIndex);
        }
        if(0 < $errorIndex) {
            return $this->parserXMLSource($responseContent, $this->ERROR_RESPONSE, $errorIndex);
        }
        return NULL;
    }
    public function parserXMLSource($responseContent, $nodeName, $nodeIndex)
    {
        $signDataStartIndex = $nodeIndex + strlen($nodeName) + 1;
        if(strrpos($responseContent, $this->ALIPAY_CERT_SN)) {
            $signIndex = strrpos($responseContent, "<" . $this->ALIPAY_CERT_SN . ">");
        } else {
            $signIndex = strrpos($responseContent, "<" . $this->SIGN_NODE_NAME . ">");
        }
        $signDataEndIndex = $signIndex - 1;
        $indexLen = $signDataEndIndex - $signDataStartIndex + 1;
        if($indexLen < 0) {
            return NULL;
        }
        return substr($responseContent, $signDataStartIndex, $indexLen);
    }
    public function checkResponseSign($request, $signData, $resp, $respObject)
    {
        if(!$this->checkEmpty($this->alipayPublicKey) || !$this->checkEmpty($this->alipayrsaPublicKey)) {
            if($signData == NULL || $this->checkEmpty($signData->sign) || $this->checkEmpty($signData->signSourceData)) {
                throw new Exception(" check sign Fail! The reason : signData is Empty");
            }
            $responseSubCode = $this->parserResponseSubCode($request, $resp, $respObject, $this->format);
            if(!$this->checkEmpty($responseSubCode) || $this->checkEmpty($responseSubCode) && !$this->checkEmpty($signData->sign)) {
                $checkResult = $this->verify($signData->signSourceData, $signData->sign, $this->alipayPublicKey, $this->signType);
                if(!$checkResult) {
                    if(!$respObject->alipay_cert_sn && $request->getApiMethodName() == "alipay.open.app.alipaycert.download") {
                        throw new Exception(" check sign Fail! The reason : alipay_cert_sn is Empty");
                    }
                    $sysParams["app_id"] = $this->appId;
                    $sysParams["format"] = $this->format;
                    $sysParams["sign_type"] = $this->signType;
                    $sysParams["method"] = "alipay.open.app.alipaycert.download";
                    $sysParams["timestamp"] = date("Y-m-d H:i:s");
                    $sysParams["alipay_sdk"] = $this->alipaySdkVersion;
                    $sysParams["terminal_type"] = $request->getTerminalType();
                    $sysParams["terminal_info"] = $request->getTerminalInfo();
                    $sysParams["prod_code"] = $request->getProdCode();
                    $sysParams["notify_url"] = $request->getNotifyUrl();
                    $sysParams["charset"] = $this->postCharset;
                    $sysParams["app_cert_sn"] = $this->appCertSN;
                    $sysParams["alipay_root_cert_sn"] = $this->alipayRootCertSN;
                    $apiParas = [];
                    $apiParas["biz_content"] = "{\"alipay_cert_sn\":\"" . $respObject->alipay_cert_sn . "\"}";
                    $apiParams = $apiParas;
                    $sysParams["sign"] = $this->generateSign(array_merge($apiParams, $sysParams), $this->signType);
                    $requestUrl = $this->gatewayUrl . "?";
                    foreach ($sysParams as $sysParamKey => $sysParamValue) {
                        $requestUrl .= $sysParamKey . "=" . urlencode($this->characet($sysParamValue, $this->postCharset)) . "&";
                    }
                    $requestUrl = substr($requestUrl, 0, -1);
                    try {
                        $resp = $this->curl($requestUrl, $apiParams);
                    } catch (Exception $e) {
                        $this->logCommunicationError($sysParams["method"], $requestUrl, "HTTP_ERROR_" . $e->getCode(), $e->getMessage());
                        return false;
                    }
                    $r = iconv($this->postCharset, $this->fileCharset . "//IGNORE", $resp);
                    $respObject = json_decode($r);
                    $resultCode = $respObject->alipay_open_app_alipaycert_download_response->code;
                    $certContent = $respObject->alipay_open_app_alipaycert_download_response->alipay_cert_content;
                    if(!empty($resultCode) && $resultCode == 10000 && !empty($certContent)) {
                        $cert = base64_decode($certContent);
                        $certCheck = true;
                        if(!empty($this->alipayRootCertContent) && $this->isCheckAlipayPublicCert) {
                            $certCheck = isTrusted($cert, $this->alipayRootCertContent);
                        }
                        if($certCheck) {
                            $pkey = openssl_pkey_get_public($cert);
                            $keyData = openssl_pkey_get_details($pkey);
                            $public_key = str_replace("-----BEGIN PUBLIC KEY-----", "", $keyData["key"]);
                            $public_key = trim(str_replace("-----END PUBLIC KEY-----", "", $public_key));
                            $this->alipayrsaPublicKey = $public_key;
                            $checkResult = $this->verify($signData->signSourceData, $signData->sign, $this->alipayrsaPublicKey, $this->signType);
                        } else {
                            throw new Exception("check sign Fail! [sign=" . $signData->sign . ", signSourceData=" . $signData->signSourceData . "]");
                        }
                    }
                    if(!$checkResult) {
                        if(0 < strpos($signData->signSourceData, "\\/")) {
                            $signData->signSourceData = str_replace("\\/", "/", $signData->signSourceData);
                            $checkResult = $this->verify($signData->signSourceData, $signData->sign, $this->alipayPublicKey, $this->signType);
                            if(!$checkResult) {
                                throw new Exception("check sign Fail! [sign=" . $signData->sign . ", signSourceData=" . $signData->signSourceData . "]");
                            }
                        } else {
                            throw new Exception("check sign Fail! [sign=" . $signData->sign . ", signSourceData=" . $signData->signSourceData . "]");
                        }
                    }
                }
            }
        }
    }
    public function parserResponseSubCode($request, $responseContent, $respObject, $format)
    {
        if("json" == $format) {
            $apiName = $request->getApiMethodName();
            $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
            $errorNodeName = $this->ERROR_RESPONSE;
            $rootIndex = strpos($responseContent, $rootNodeName);
            $errorIndex = strpos($responseContent, $errorNodeName);
            if(0 < $rootIndex) {
                $rInnerObject = $respObject->{$rootNodeName};
            } elseif(0 < $errorIndex) {
                $rInnerObject = $respObject->{$errorNodeName};
            } else {
                return NULL;
            }
            if(isset($rInnerObject->sub_code)) {
                return $rInnerObject->sub_code;
            }
            return NULL;
        }
        if("xml" == $format) {
            return $respObject->sub_code;
        }
    }
    public function verify($data, $sign, $rsaPublicKeyFilePath, $signType = "RSA")
    {
        if($this->checkEmpty($this->alipayPublicKey)) {
            $pubKey = $this->alipayrsaPublicKey;
            $res = "-----BEGIN PUBLIC KEY-----\n" . wordwrap($pubKey, 64, "\n", true) . "\n-----END PUBLIC KEY-----";
        } else {
            $pubKey = file_get_contents($rsaPublicKeyFilePath);
            $res = openssl_get_publickey($pubKey);
        }
        $res or exit("支付宝RSA公钥错误。请检查公钥文件格式是否正确");
        $result = false;
        if("RSA2" == $signType) {
            $result = openssl_verify($data, base64_decode($sign), $res, OPENSSL_ALGO_SHA256) === 1;
        } else {
            $result = openssl_verify($data, base64_decode($sign), $res) === 1;
        }
        if(!$this->checkEmpty($this->alipayPublicKey)) {
            openssl_free_key($res);
        }
        return $result;
    }
    private function encryptJSONSignSource($request, $responseContent)
    {
        $parsetItem = $this->parserEncryptJSONSignSource($request, $responseContent);
        $bodyIndexContent = substr($responseContent, 0, $parsetItem->startIndex);
        $bodyEndContent = substr($responseContent, $parsetItem->endIndex, strlen($responseContent) + 1 - $parsetItem->endIndex);
        $bizContent = decrypt($parsetItem->encryptContent, $this->encryptKey);
        return $bodyIndexContent . $bizContent . $bodyEndContent;
    }
    private function parserEncryptJSONSignSource($request, $responseContent)
    {
        $apiName = $request->getApiMethodName();
        $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
        $rootIndex = strpos($responseContent, $rootNodeName);
        $errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
        if(0 < $rootIndex) {
            return $this->parserEncryptJSONItem($responseContent, $rootNodeName, $rootIndex);
        }
        if(0 < $errorIndex) {
            return $this->parserEncryptJSONItem($responseContent, $this->ERROR_RESPONSE, $errorIndex);
        }
        return NULL;
    }
    private function parserEncryptJSONItem($responseContent, $nodeName, $nodeIndex)
    {
        $signDataStartIndex = $nodeIndex + strlen($nodeName) + 2;
        if(strrpos($responseContent, $this->ALIPAY_CERT_SN)) {
            $signIndex = strpos($responseContent, "\"" . $this->ALIPAY_CERT_SN . "\"");
        } else {
            $signIndex = strpos($responseContent, "\"" . $this->SIGN_NODE_NAME . "\"");
        }
        $signDataEndIndex = $signIndex - 1;
        if($signDataEndIndex < 0) {
            $signDataEndIndex = strlen($responseContent) - 1;
        }
        $indexLen = $signDataEndIndex - $signDataStartIndex;
        $encContent = substr($responseContent, $signDataStartIndex + 1, $indexLen - 2);
        $encryptParseItem = new EncryptParseItem();
        $encryptParseItem->encryptContent = $encContent;
        $encryptParseItem->startIndex = $signDataStartIndex;
        $encryptParseItem->endIndex = $signDataEndIndex;
        return $encryptParseItem;
    }
    private function encryptXMLSignSource($request, $responseContent)
    {
        $parsetItem = $this->parserEncryptXMLSignSource($request, $responseContent);
        $bodyIndexContent = substr($responseContent, 0, $parsetItem->startIndex);
        $bodyEndContent = substr($responseContent, $parsetItem->endIndex, strlen($responseContent) + 1 - $parsetItem->endIndex);
        $bizContent = decrypt($parsetItem->encryptContent, $this->encryptKey);
        return $bodyIndexContent . $bizContent . $bodyEndContent;
    }
    private function parserEncryptXMLSignSource($request, $responseContent)
    {
        $apiName = $request->getApiMethodName();
        $rootNodeName = str_replace(".", "_", $apiName) . $this->RESPONSE_SUFFIX;
        $rootIndex = strpos($responseContent, $rootNodeName);
        $errorIndex = strpos($responseContent, $this->ERROR_RESPONSE);
        if(0 < $rootIndex) {
            return $this->parserEncryptXMLItem($responseContent, $rootNodeName, $rootIndex);
        }
        if(0 < $errorIndex) {
            return $this->parserEncryptXMLItem($responseContent, $this->ERROR_RESPONSE, $errorIndex);
        }
        return NULL;
    }
    private function parserEncryptXMLItem($responseContent, $nodeName, $nodeIndex)
    {
        $signDataStartIndex = $nodeIndex + strlen($nodeName) + 1;
        $xmlStartNode = "<" . $this->ENCRYPT_XML_NODE_NAME . ">";
        $xmlEndNode = "</" . $this->ENCRYPT_XML_NODE_NAME . ">";
        $indexOfXmlNode = strpos($responseContent, $xmlEndNode);
        if($indexOfXmlNode < 0) {
            $item = new EncryptParseItem();
            $item->encryptContent = NULL;
            $item->startIndex = 0;
            $item->endIndex = 0;
            return $item;
        }
        $startIndex = $signDataStartIndex + strlen($xmlStartNode);
        $bizContentLen = $indexOfXmlNode - $startIndex;
        $bizContent = substr($responseContent, $startIndex, $bizContentLen);
        $encryptParseItem = new EncryptParseItem();
        $encryptParseItem->encryptContent = $bizContent;
        $encryptParseItem->startIndex = $signDataStartIndex;
        $encryptParseItem->endIndex = $indexOfXmlNode + strlen($xmlEndNode);
        return $encryptParseItem;
    }
    public function echoDebug($content)
    {
        if($this->debugInfo) {
            echo "<br/>" . $content;
        }
    }
}

?>